const fs = require('fs');
const path = require('path');
const Controller = require('egg').Controller;
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');

class CommonClass extends Controller {
    constructor(props) {
        super(props);
    }
    async upload() {
        const stream = await this.ctx.getFileStream();
        const filename = Date.parse(new Date()).toString() + '.jpg'
        const target = path.join(this.config.baseDir, 'app/public', filename);
        const writeStream = fs.createWriteStream(target);
        try {
            await awaitWriteStream(stream.pipe(writeStream));
        } catch (err) {
            await sendToWormhole(stream);
            throw err;
        }

        this.ctx.body = { status: 0, message: { url: '/public/' + filename } };
    }
}
module.exports = CommonClass;
